<script lang="ts" setup>
import daglService from '@/api/dagl'
import zzjgService from '@/api/zzjg'
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import Chart from '@/components/charts/index.vue'
import { TableItem } from '@/api/common'
import dayjs from 'dayjs'
import pinyin from 'pinyin-match'
import { useMainStore } from '@/store/main'
const mainStore = useMainStore()
// 入参
defineProps({
  optionsObj: {
    type: Object,
    default: () => ({}),
  },
})
// loading
const loading = ref<boolean>(false)
const organizationList = ref([])
zzjgService.getDwbm({ dwbm: mainStore.userInfo.dwbm }).then((res: any) => {
  organizationList.value = res.data.data
  form.value.dwbhList.push(res.data.data[0].dwbm)
})

// 表格数据
const tableData = ref<TableItem>({
  data: [],
  titles: [
    {
      label: '档案所属院',
      prop: 'cbdwmc',
      width: 200,
      custom: true,
    },
    { label: '诉讼档案(件)', prop: 'ssdasl', width: 120 },
    { label: '占比(%)', prop: 'ssdazb', width: 100 },
    { label: '视频档案(件)', prop: 'spsl', width: 120 },
    { label: '占比(%)', prop: 'spslzb', width: 100 },
    { label: '音频档案(件)', prop: 'ypsl', width: 120 },
    { label: '占比(%)', prop: 'ypslzb', width: 100 },
    { label: '照片档案(件)', prop: 'zpsl', width: 120 },
    { label: '占比(%)', prop: 'zpslzb', width: 100 },
    { label: '总计(件)', prop: 'zs', width: 100 },
  ],
})
const display = ref('table')
// 查询条件
const form = ref<{
  dwbhList: string[]
  dwbm: string
  bmbm: string
  gdjsrq: string
  gdksrq: string
}>({
  dwbhList: [],
  dwbm: '',
  bmbm: '',
  gdjsrq: '',
  gdksrq: '',
})
// 查询条件表单实例
const filterFormRef = ref()
// 归档日期
const createTime = ref()

const getTableData = () => {
  const params = {
    dwbhList: form.value.dwbhList,
    gdksrq: createTime.value?.length ? dayjs(createTime.value[0]).format('YYYY-MM-DD') : '',
    gdjsrq: createTime.value?.length ? dayjs(createTime.value[1]).format('YYYY-MM-DD') : '',
  }
  loading.value = true
  daglService
    .queryTjdwdasl(params)
    .then((res) => {
      if (res) {
        tableData.value.data = res.data
      }
    })
    .catch((err) => {
      !err.isError && ElMessage({ type: 'warning', message: err.message })
    })
    .finally(() => {
      loading.value = false
    })
}
getTableData()

const getBmTableData = () => {
  const params = {
    dwbm: form.value.dwbm,
    gdksrq: createTime.value?.length ? dayjs(createTime.value[0]).format('YYYY-MM-DD') : '',
    gdjsrq: createTime.value?.length ? dayjs(createTime.value[1]).format('YYYY-MM-DD') : '',
  }
  loading.value = true
  daglService
    .queryTjbmdasl(params)
    .then((res) => {
      if (res) {
        tableData.value.data = res.data
      }
    })
    .catch((err) => {
      !err.isError && ElMessage({ type: 'warning', message: err.message })
    })
    .finally(() => {
      loading.value = false
    })
}

const getRyTableData = () => {
  const params = {
    bmbm: form.value.bmbm,
    gdksrq: createTime.value?.length ? dayjs(createTime.value[0]).format('YYYY-MM-DD') : '',
    gdjsrq: createTime.value?.length ? dayjs(createTime.value[1]).format('YYYY-MM-DD') : '',
  }
  loading.value = true
  daglService
    .queryTjrydasl(params)
    .then((res) => {
      if (res) {
        tableData.value.data = res.data
      }
    })
    .catch((err) => {
      !err.isError && ElMessage({ type: 'warning', message: err.message })
    })
    .finally(() => {
      loading.value = false
    })
}

const dwmx = ref()
const pieInfo = ref()
const showDetail = ref(false)
const queryTjdwmxdasl = () => {
  const params = {
    dwbm: form.value.dwbm,
    gdksrq: createTime.value?.length ? dayjs(createTime.value[0]).format('YYYY-MM-DD') : '',
    gdjsrq: createTime.value?.length ? dayjs(createTime.value[1]).format('YYYY-MM-DD') : '',
  }
  loading.value = true
  daglService
    .queryTjdwmxdasl(params)
    .then((res) => {
      if (res) {
        pieInfo.value = res.data
        dwmx.value = res.data
          ? [
              {
                name: '诉讼档案',
                value: res.data.ssdasl + 10,
                pct: res.data.ssdazb,
              },
              {
                name: '视频档案',
                value: res.data.spsl + 100,
                pct: res.data.spslzb,
              },
              {
                name: '音频档案',
                value: res.data.ypsl + 90,
                pct: res.data.ypslzb,
              },
              {
                name: '照片档案',
                value: res.data.zpsl + 80,
                pct: res.data.zpslzb,
              },
            ]
          : []
      }
    })
    .catch((err) => {
      !err.isError && ElMessage({ type: 'warning', message: err.message })
    })
    .finally(() => {
      loading.value = false
    })
}

const getChartDetail = (chartData: any) => {
  const item = tableData.value.data.find(
    (el) =>
      (el.cbdwbm || el.cbjcgbh || el.cbbmbm) &&
      (el.cbdwmc || el.cbbmmc || el.cbjcg) === chartData.name,
  )
  form.value.dwbm = item.cbdwbm || item.cbjcgbh || item.cbbmbm
  queryTjdwmxdasl()
  showDetail.value = true
}

const displayChange = (val: string) => {
  if (val === 'table') {
    showDetail.value = false
  }
}
const filterFn = (value: string, data: any, node: any) => {
  if (value) return pinyin.match(node.label, value)
  return true
}

// 表格是以下钻形式查数据
// 单位层级1，部门2，人员3
const currentLevel = ref(1)
const dwInfo = ref()
const bmInfo = ref()
const checkRowClick = (row?: any) => {
  switch (currentLevel.value) {
    case 1:
      getTableData()
      tableData.value.titles[0] = {
        label: '档案所属院',
        prop: 'cbdwmc',
        width: 200,
        custom: true,
      }
      break
    case 2:
      form.value.dwbm = row.cbdwbm
      dwInfo.value = row
      getBmTableData()
      tableData.value.titles[0] = {
        label: '归档部门',
        prop: 'cbbmmc',
        width: 200,
        custom: true,
      }
      break
    case 3:
      form.value.bmbm = row.cbbmbm
      bmInfo.value = row
      getRyTableData()
      tableData.value.titles[0] = {
        label: '归档人',
        prop: 'cbjcg',
        width: 200,
      }
      break
  }
}
const preStep = (e: Event) => {
  e.preventDefault()
  if (showDetail.value) {
    showDetail.value = false
    return
  }
  currentLevel.value--
  if (currentLevel.value === 1) {
    checkRowClick()
  } else if (currentLevel.value === 2) {
    checkRowClick(dwInfo.value)
  }
}

// 单位层级刷新
const curren1Refresh = () => {
  getTableData()
}

const curren2Refresh = (e: Event) => {
  e.preventDefault()
  if (currentLevel.value === 2) {
    getBmTableData()
  }

  if (currentLevel.value === 3) {
    getRyTableData()
  }

  if (showDetail.value) {
    queryTjdwmxdasl()
  }
}
</script>
<template>
  <div class="container">
    <!--表单-->
    <div class="form-box">
      <el-form :model="form" ref="filterFormRef" inline label-width="100px">
        <el-form-item
          v-if="currentLevel === 1 && !showDetail"
          prop="dwbhList"
          :rules="[
            {
              required: true,
              message: '必选',
            },
          ]"
          label="档案所属院:"
        >
          <el-tree-select
            style="width: 300px"
            v-model="form.dwbhList"
            multiple
            :props="{
              children: 'children',
              label: 'dwmc',
              value: 'dwbm',
            }"
            :data="organizationList"
            check-strictly
            default-expand-all
            :filter-node-method="filterFn"
            filterable
          >
          </el-tree-select>
        </el-form-item>
        <el-form-item v-if="currentLevel === 1 && !showDetail" label="归档日期">
          <el-date-picker
            style="width: 240px"
            v-model="createTime"
            type="daterange"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
          />
        </el-form-item>

        <el-form-item v-if="currentLevel === 2 && !showDetail">
          <span class="zzjg">{{ dwInfo.cbdwmc }}</span>
        </el-form-item>
        <el-form-item v-if="currentLevel === 3 && !showDetail">
          <span class="zzjg">{{ bmInfo.cbbmmc }}</span>
        </el-form-item>

        <el-form-item v-if="!showDetail">
          <el-radio-group v-model="display" @change="displayChange">
            <el-radio-button label="统计表" value="table" />
            <el-radio-button label="统计图" value="chart" />
          </el-radio-group>
        </el-form-item>

        <el-form-item> </el-form-item>

        <el-form-item class="dwmcInfo">
          <div class="dwmcInfoTitle">
            <span v-if="showDetail" class="zzjg">{{ pieInfo?.cbdwmc }}</span>
          </div>
          <div class="dwmcInfoButton">
            <button
              class="btn_operation"
              v-if="showDetail || currentLevel == 2 || currentLevel == 3"
            >
              <div class="btn-export"></div>
              导出
            </button>
            <button
              class="btn_operation"
              @click="curren2Refresh"
              v-if="showDetail || currentLevel == 2 || currentLevel == 3"
            >
              <div class="btn-refresh"></div>
              刷新
            </button>
            <button
              class="btn_operation"
              @click="preStep"
              v-if="!(currentLevel === 1 && !showDetail)"
            >
              <div class="btn-back"></div>
              返回
            </button>
          </div>
        </el-form-item>

        <el-form-item class="search" v-if="currentLevel === 1 && !showDetail">
          <el-button type="primary" @click="getTableData">查询</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="button-group" v-if="currentLevel == 1 && !showDetail">
      <button class="btn_operation">
        <div class="btn-export"></div>
        导出
      </button>
      <button class="btn_operation" @click="curren1Refresh">
        <div class="btn-refresh"></div>
        刷新
      </button>
    </div>
    <!--表格-->
    <div class="table-box" v-if="display === 'table'">
      <el-table :data="tableData.data" stripe row-key="id" height="100%" v-loading="loading">
        <el-table-column
          v-for="column in tableData.titles"
          :key="column.prop"
          :prop="column.prop"
          :label="column.label"
        >
          <template #default="{ row }">
            <div v-if="column.custom">
              <el-link
                type="primary"
                class="custom-link"
                :underline="false"
                @click="
                  () => {
                    currentLevel++
                    checkRowClick(row)
                  }
                "
                >{{ row[column.prop] }}</el-link
              >
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="chart-box" v-else>
      <Chart v-if="showDetail" chartType="pie" :chartData="dwmx"></Chart>
      <Chart
        v-else
        chartType="bar"
        @click-chart="getChartDetail"
        :chartData="tableData.data"
      ></Chart>
    </div>
  </div>
</template>
<style lang="scss" scoped>
.container {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  .form-box {
    .zzjg {
      font-size: 20px;
      padding-right: 8px;
    }
    .el-form {
      display: flex;
      .el-form-item.dwmcInfo {
        flex: 1;
        width: 100%;
        display: flex;
        .dwmcInfoTitle {
          flex: 5;
        }
        .dwmcInfoButton {
          display: flex;
          flex: 2;
          justify-content: flex-end;
        }
      }
    }
  }
  .chart-box,
  .table-box {
    flex: 1;
    // height: calc(100% - 60px);
  }
  .custom-link {
    width: 100%;
    display: block;
    white-space: nowrap;
    text-overflow: ellipsis;
    overflow: hidden;
    .el-link__inner {
      display: inline;
    }
  }
}

.button-group {
  display: flex;
  justify-content: flex-end;
  margin-right: 32px;
  margin-bottom: 10px;
}
</style>
